import os
import json
from django.db import models
from django.urls import reverse

# Create your models here.
class BaseModel(models.Model):
    addtime = models.DateTimeField('添加时间', auto_now_add=True)
    uptime = models.DateTimeField('更新时间', auto_now=True)
    enabled = models.BooleanField('更新时间', default=True)
    
    class Meta:
        abstract = True


class AuthorManage(models.Manager):
    def insert_author(self, path):
        with open(path, 'r') as f:
            data = json.load(f)
        for d in data:
            self.get_or_create(name=d.get('name'), description=d.get('description'), sdescription=d.get('short_description'))


class BaseStationModel(BaseModel):
    name = models.CharField('名称', max_length=20, null=False, default='')
    description = models.CharField('介绍', max_length=512, null=True, blank=True, default='')
    sdescription = models.CharField('短介绍', max_length=512, null=True, blank=True, default='')

    class Meta:
        abstract = True

class AuthorModel(BaseStationModel):
    objects = AuthorManage()

    class Meta:
        db_table = 'ci_author'
        verbose_name = '作者'
        verbose_name_plural = verbose_name
        ordering = ['-id']

    def __str__(self):
        return self.name

class SeriesModel(BaseStationModel):
    '''文章集结成册 书的概念'''
    author = models.ForeignKey(to='AuthorModel', on_delete=models.CASCADE, null=True)
    station = models.ForeignKey(to='StationModel', on_delete=models.CASCADE, null=True)

    class Meta:
        db_table = 'ci_series'
        verbose_name = '系列'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class StationModel(BaseStationModel):
    '''分类'''
    class Meta:
        db_table = 'ci_station'
        verbose_name = '分类'
        verbose_name_plural = verbose_name
    
    def __str__(self):
        return self.name

class ArticleManage(models.Manager):
    def insert_article(self, path):
        for file_name in os.listdir(path):
            with open(os.path.join(path, file_name), 'r') as f:
                datas = json.load(f)
            for d in datas:
                author = d.pop('author')
                try:
                    author, _ = AuthorModel.objects.get_or_create(name=author)
                except Exception:
                    author = AuthorModel.objects.filter(name=author).first()
                try:
                    title = d.pop('rhythmic'),
                    content = d.pop('paragraphs'),
                except KeyError:
                    with open('/data/www/songs/errordata.json', 'a') as f:
                        json.dump(d, f)
                ad = {
                    'title': title[0],
                    'content': '\n'.join(content[0]),
                    'author': author,
                } 
                self.create(**ad)

    def push_baidu_article(self, reverse=True):
        if reverse:
            queryset = self.filter(is_push_ad__regex="^1")
        else:
            queryset = self.filter(is_push_ad__regex="^0")
        return queryset

class ArticleModels(BaseModel):
    title = models.CharField('标题', max_length=512, null=False, default='无题')   
    content = models.CharField('正文', max_length=1024, null=False, default='') 
    author = models.ForeignKey(to=AuthorModel, on_delete=models.CASCADE, verbose_name='作者')
    tags = models.CharField('分类', max_length=128, null=True,  default='')
    series = models.ForeignKey(to=SeriesModel, on_delete=models.CASCADE, verbose_name='系列', null=True)
    station = models.ForeignKey(to=StationModel, on_delete=models.CASCADE, verbose_name='分类', null=True)
    series_sort = models.IntegerField('系列排序', null=True, default=-1)
    is_push_ad = models.CharField("搜索引擎推送", max_length=20, null=False, default='00000000000000000000') 

    objects = ArticleManage()

    class Meta:
        db_table = 'ci_article'
        verbose_name = '古诗词'
        verbose_name_plural = verbose_name
        ordering = ['-id']

    def __str__(self):
        return self.title

    def save(self,update_fields=None, *args, **kwargs):
        content = None
        if len(self.content) >= 500:
            content, self.content = self.content, "-1"
        super().save(*args, **kwargs)
        if content:
            ArticleContentModel.objects.get_or_create(title_id=self.id, content=content)

    def is_push_baidu(self):
        """检查是否已经推送百度"""
        if '1' == self.is_push_ad[0]:
            return True
        else:
            return False
    
    def set_baidu_sign(self, sign=True):
        if not sign == self.is_push_baidu():
            _ = list(self.is_push_ad)
            _[0] = "1"
            self.is_push_ad = ''.join(_)
            self.save()

    def link(self):
        return f"https://www.gmclqb.cn/tool/article_detail/{self.id}.html"
     
    def get_content(self):
        if self.content == '-1':
            self.content = ArticleContentModel.objects.get(title=self).content
        return self.content

class ArticleContentModel(BaseModel):
    title = models.OneToOneField('ArticleModels', on_delete=models.CASCADE, verbose_name='文章标题')
    content = models.TextField('正文')

    class Meta:
        db_table = "ci_article_content"
    
    def __str__(self):
        return self.title.title

